package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //x轴:日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        log.info("x轴日期:{}",dateList);
        //y轴:每天的营业额
        ArrayList<Double> turnoverList = new ArrayList<>();
        dateList.forEach(localDate -> {
            //yyyy-MM-dd 00:00:00
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //yyyy-MM-dd 23:59:59
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询营业额
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", beginTime);
            map.put("endTime",endTime);
            Double turnover = orderMapper.getTurnover(map);
            //将查询到的营业额放入turnoverList
            turnover=turnover==null? 0.0:turnover;
            turnoverList.add(turnover);
        });
        log.info("y轴营业额:{}",turnoverList);

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .turnoverList(StringUtils.join(turnoverList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //x轴:日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //y轴:用户总量
        ArrayList<Integer> totalUserList = new ArrayList<>();
        //y轴:今日新增用户
        ArrayList<Integer> newUserList = new ArrayList<>();

        dateList.forEach(localDate -> {
            //yyyy-MM-dd 00:00:00
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //yyyy-MM-dd 23:59:59
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询今日新增用户
            Integer newUser = userMapper.getUserCount(beginTime,endTime);
            newUser=newUser==null? 0:newUser;
            //用户总量
            Integer totalUser = userMapper.getUserCount(null,endTime);
            totalUser=totalUser==null? 0:totalUser;

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        });
        log.info("用户总量:{}",totalUserList);

        //封装返回
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //x轴:日期
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //每日总订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //每日有效订单(已完成订单)
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //每日总订单数
            Integer orderCount = orderMapper.getOrderCount(beginTime,endTime,null);
            orderCountList.add(orderCount);
            //每日有效订单(已完成订单)
            Integer validOrderCount = orderMapper.getOrderCount(beginTime,endTime,Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        }
        log.info("每日总订单数:{}",orderCountList);
        log.info("每日有效订单:{}",validOrderCountList);

        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ",")) //日期列表
                .orderCountList(StringUtils.join(orderCountList, ",")) //订单数列表
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))  //有效订单数列表
                .totalOrderCount(totalOrderCount) //订单总数
                .validOrderCount(validOrderCount) //有效订单总数
                .orderCompletionRate(orderCompletionRate) //订单完成率
                .build();
        return orderReportVO;
    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //30天前
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //添加时分秒
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");

        try {
            //创建excel文件对象
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获取页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //填充数据-时间
            sheet1.getRow(1).getCell(0).setCellValue("时间:"+dateBegin+"至"+dateEnd);
            //获得第四行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(1).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getNewUsers());
            //获得第五行
            row=sheet1.getRow(4);
            row.getCell(1).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(3).setCellValue(businessDataVO.getUnitPrice());
            //填充明细数据(从dateBegin开始遍历30天)
            for (int i = 0; i < 30; i++) {
                LocalDate localDate = dateBegin.plusDays(i);
                //查询当天营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(
                        LocalDateTime.of(localDate, LocalTime.MIN),
                        LocalDateTime.of(localDate,LocalTime.MAX));
                //获得一行
                row=sheet1.getRow(7+i);
                row.getCell(0).setCellValue(localDate.toString());
                row.getCell(1).setCellValue(businessData.getTurnover());
                row.getCell(2).setCellValue(businessData.getValidOrderCount());
                row.getCell(3).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(4).setCellValue(businessData.getUnitPrice());
                row.getCell(5).setCellValue(businessData.getNewUsers());

            }

            //下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);
            //关闭资源
            excel.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
